import Mock from 'mockjs'
// get请求从config.url获取参数，post从config.body中获取参数
function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}
/* 订单列表 */
let orderList = []
const count = 100
for (let i = 0; i < count; i++) {
  orderList.push(
    Mock.mock({
      orderId: Mock.Random.guid(), //订单编号
      orderPrice: Mock.Random.integer(100, 2000), //订单价格
      'isPay|1': ['1', '0', '-1'], //是否付款
      isSend: Mock.Random.boolean(), //是否发货
      addr: Mock.mock('@county(true)'), //发货地址
      time: Mock.Random.time('yyyy-MM-dd HH:mm:ss'), //下单时间
    })
  )
}

export default {
  /**
   *获取订单列表
   *需要携带参数 goodName,page,limt(分页大小)
   * @param id,page,limit
   * @return {{code:number,count:number,data:*[]}}
   **/
  getOrder: (config) => {
    const { orderId, page = 1, pagesize = 20 } = param2Obj(config.url)
    const mockList = orderList.filter((order) => {
      if (orderId && order.orderId.indexOf(orderId) === -1 && order.addr.indexOf(orderId) === -1) return false
      return true
    })
    const pageList = mockList.filter((item, index) => index < pagesize * page && index >= pagesize * (page - 1))
    return {
      code: 200,
      count: mockList.length,
      data: pageList,
      message: '获取商品列表成功',
    }
  },
  /* 
  获取所有订单
  */
  getisPay: (config) => {
    return {
      code: 200,
      data: orderList,
      message: '获取所有订单成功',
    }
  },
  /**
   * 增加商品
   * @param name, addr, age, birth, sex
   * @return {{code: number, data: {message: string}}}
   */
  addOrder: (config) => {
    const { orderId, orderPrice, isPay, isSend, addr, time } = JSON.parse(config.body)
    orderList.unshift({
      orderId: orderId,
      orderPrice: orderPrice,
      isPay: isPay,
      isSend: isSend,
      addr: addr,
      time: time,
    })
    return {
      code: 201,
      data: {
        message: '添加成功',
      },
    }
  },
  /**
   * 删除订单
   * @param id
   * @return {*}
   */
  deleteOrder: (config) => {
    const orderId = config.body
    if (!orderId) {
      return {
        code: 400,
        message: '参数不正确',
      }
    } else {
      orderList = orderList.filter((u) => u.orderId !== orderId)
      return {
        code: 200,
        message: '删除成功',
      }
    }
  },
  /**
   * 修改订单
   * @param id, goodPic, goodName, goodInfo, price, num, createTime
   * @return {{code: number, data: {message: string}}}
   */
  editOrder: (config) => {
    const { orderId, orderPrice, isPay, isSend, addr, time } = JSON.parse(config.body)
    orderList.some((u) => {
      if (u.orderId === orderId) {
        ;(u.orderId = orderId), (u.orderPrice = orderPrice), (u.isPay = isPay), (u.isSend = isSend), (u.addr = addr), (u.time = time)
        return true
      }
    })
    return {
      code: 201,
      data: {
        message: '修改成功',
      },
    }
  },
}
